﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace GenericControlsWinForm
{
    public class DateTextBox : TextBox
    {
        public DateTextBox()
        {
            this.KeyDown += new KeyEventHandler(DateTextBox_KeyDown);
            this.LostFocus += new EventHandler(DateTextBox_LostFocus);
            this.MaxLength = 10;
            this.Width = 80;
        }

        void DateTextBox_LostFocus(object sender, EventArgs e)
        {
            try
            {
                if (String.IsNullOrEmpty(this.Text))
                    return;

                DateTime data = Convert.ToDateTime(this.Text);
            }
            catch (Exception)
            {
                MessageBox.Show("Data inválida.");
                this.Text = string.Empty;
            }
        }

        void DateTextBox_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (CommomValidator.KeyIsNumber(e.KeyCode))
                {
                    string lastString = (sender as DateTextBox).Text;

                    if (lastString.Length == 2 || lastString.Length == 5)
                    {
                        lastString += "/";
                        ((DateTextBox)sender).Text = lastString;
                        ((DateTextBox)sender).SelectionStart = ((DateTextBox)sender).Text.Length;
                    }
                }
                else
                {
                    if(e.KeyCode != Keys.Tab)
                        e.Handled = true;
                }
            }
            catch (Exception)
            {
                throw new Exception("Erro no componente DateTime");
            }
        }
    }
}
